//
//  AMInstanceDetailView.m
//  AWSMobile
//
//  Created by James on 14-11-13.
//  Copyright (c) 2014年 Siemens. All rights reserved.
//

#import "AMInstanceDetailView.h"
#import <AWSiOSSDKv2/AWSEC2.h>
#import <Bolts/BFTask.h>
#import <Bolts/BFExecutor.h>

#import "AWSEC2Instance+Extension.h"
#import "AMFunctions.h"

@interface AMInstanceDetailView ()

@property AWSEC2RebootInstancesRequest *rebootRequest;
@property AWSEC2StopInstancesRequest *stopRequest;
@property AWSEC2StartInstancesRequest *startRequest;
@property AWSEC2TerminateInstancesRequest *terminateRequest;
@property AWSEC2DescribeInstancesRequest *describeRequest;

@end

@implementation AMInstanceDetailView

#pragma mark - Life cycle
- (void)viewWillAppear:(BOOL)animated
{
    _scrollView.contentSize = CGSizeMake(320, 480);
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (_rebootRequest)
    {
        [_rebootRequest cancel];
        _rebootRequest = nil;
    }
    if (_stopRequest)
    {
        [_stopRequest cancel];
        _stopRequest = nil;
    }
    if (_startRequest)
    {
        [_startRequest cancel];
        _startRequest = nil;
    }
    if (_terminateRequest)
    {
        [_terminateRequest cancel];
        _terminateRequest = nil;
    }
    if (_describeRequest)
    {
        [_describeRequest cancel];
        _describeRequest = nil;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIColor *textColor = [UIColor colorWithHexString:@"656565"];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, 320, 367)];
    _scrollView.scrollEnabled = YES;
    
    UILabel *instanceID = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 97, 21)];
    instanceID.text = @"Instance ID";
    instanceID.textColor = textColor;
    instanceID.font = [UIFont boldSystemFontOfSize:17];
    
    _instanceID = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 237, 21)];
    _instanceID.textColor = textColor;
    _instanceID.font = [UIFont systemFontOfSize:17];
    
    UILabel *publicDNS = [[UILabel alloc] initWithFrame:CGRectMake(10, 70, 97, 21)];
    publicDNS.text = @"Public DNS";
    publicDNS.textColor = textColor;
    publicDNS.font = [UIFont boldSystemFontOfSize:17];
    
    NSString *publicDNSName = _instance.publicDnsName;
    CGSize dnsNameSize = CGSizeMake(237, 21);
    if (!publicDNSName || ![publicDNSName isEqualToString:@""])
    {
        dnsNameSize = CGSizeMake(237, 42);
    }
    else
        publicDNSName = @"-";
    
    _instancePublicDNS = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 237, dnsNameSize.height)];
    _instancePublicDNS.textColor = textColor;
    _instancePublicDNS.text = publicDNSName;
    _instancePublicDNS.font = [UIFont systemFontOfSize:17];
    _instancePublicDNS.numberOfLines = 2;
    _instancePublicDNS.lineBreakMode = NSLineBreakByWordWrapping;
    
    CGFloat dnsNameFix = _instancePublicDNS.frame.origin.y + dnsNameSize.height+10;
    
    UILabel *publicIP = [[UILabel alloc] initWithFrame:CGRectMake(10, dnsNameFix, 77, 21)];
    publicIP.text = @"Public IP";
    publicIP.textColor = textColor;
    publicIP.font = [UIFont boldSystemFontOfSize:17];
    
    _instancePublicIP = [[UILabel alloc] initWithFrame:CGRectMake(10, dnsNameFix+30, 237, 21)];
    _instancePublicIP.textColor = textColor;
    _instancePublicIP.font = [UIFont systemFontOfSize:17];
    
    UILabel *zone = [[UILabel alloc] initWithFrame:CGRectMake(10, dnsNameFix+60, 46, 21)];
    zone.text = @"Zone";
    zone.textColor = textColor;
    zone.font = [UIFont boldSystemFontOfSize:17];
    
    _instanceAailableZone = [[UILabel alloc] initWithFrame:CGRectMake(10, dnsNameFix+90, 237, 21)];
    _instanceAailableZone.textColor = textColor;
    _instanceAailableZone.font = [UIFont systemFontOfSize:17];
    
    
    UILabel *statesChecks = [[UILabel alloc] initWithFrame:CGRectMake(10, dnsNameFix+120, 125, 21)];
    statesChecks.text = @"Status Checks";
    statesChecks.textColor = textColor;
    statesChecks.font = [UIFont boldSystemFontOfSize:17];
    
    _instanceStatusChecks = [[UILabel alloc] initWithFrame:CGRectMake(10, dnsNameFix+150, 237, 21)];
    _instanceStatusChecks.textColor = textColor;
    _instanceStatusChecks.font = [UIFont systemFontOfSize:17];
    
    _instanceStateName = [[UILabel alloc] initWithFrame:CGRectMake(191, 10, 118, 21)];
    _instanceStateName.font = [UIFont systemFontOfSize:17];
    _instanceStateName.textAlignment = NSTextAlignmentRight;
    
    _instanceRebootButton = [[UIButton alloc] initWithFrame:CGRectMake(10, dnsNameFix + 180, 300, 40)];
    [_instanceRebootButton setBackgroundColor:[UIColor colorWithHexString:@"36b2af"]];
    [_instanceRebootButton addTarget:self action:@selector(reboot:) forControlEvents:UIControlEventTouchUpInside];
    
    _instanceStopButton = [[UIButton alloc] initWithFrame:CGRectMake(10, dnsNameFix + 230, 300, 40)];
    [_instanceStopButton setBackgroundColor:[UIColor colorWithHexString:@"36b2af"]];
    [_instanceStopButton addTarget:self action:@selector(stopOrStart:) forControlEvents:UIControlEventTouchUpInside];
    
    _instanceTerminateButton = [[UIButton alloc] initWithFrame:CGRectMake(10, dnsNameFix + 280, 300, 40)];
    [_instanceTerminateButton setBackgroundColor:[UIColor colorWithHexString:@"e65d65"]];
    [_instanceTerminateButton addTarget:self action:@selector(terminate:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self loadInstanceDetails];
    
    [_scrollView addSubview:instanceID];
    [_scrollView addSubview:publicDNS];
    [_scrollView addSubview:publicIP];
    [_scrollView addSubview:zone];
    [_scrollView addSubview:statesChecks];
    [_scrollView addSubview:_instanceID];
    [_scrollView addSubview:_instancePublicDNS];
    [_scrollView addSubview:_instancePublicIP];
    [_scrollView addSubview:_instanceAailableZone];
    [_scrollView addSubview:_instanceStatusChecks];
    [_scrollView addSubview:_instanceStateName];
    
    [_scrollView addSubview:_instanceRebootButton];
    [_scrollView addSubview:_instanceStopButton];
    [_scrollView addSubview:_instanceTerminateButton];
    
    [self.view addSubview:_scrollView];
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Actions

- (void)loadInstanceDetails
{
    _instanceID.text = _instance.instanceId;
    
    NSString *publicIPAddress = [_instance publicIpAddress];
    if (!publicIPAddress)
    {
        publicIPAddress = @"-";
    }
    _instancePublicIP.text = publicIPAddress;
    _instanceAailableZone.text = _instance.placement.availabilityZone;
    _instanceStatusChecks.text = @"";
    _instanceStateName.text = [_instance stateName];
    [_instanceRebootButton setTitle:@"REBOOT" forState:UIControlStateNormal];
    [_instanceTerminateButton setTitle:@"TERMINATE" forState:UIControlStateNormal];
    
    if (_instance.state.name == AWSEC2InstanceStateNameRunning)
    {
        _instanceStateName.textColor = [UIColor colorWithHexString:@"36b2af"];
        [_instanceStopButton setTitle:@"STOP" forState:UIControlStateNormal];
        [_instanceRebootButton setBackgroundColor:[UIColor colorWithHexString:@"36b2af"]];
        [_instanceTerminateButton setBackgroundColor:[UIColor colorWithHexString:@"e65d65"]];
        _instanceRebootButton.enabled = YES;
        _instanceTerminateButton.enabled = YES;
    }
    else
    {
        [_instanceStopButton setTitle:@"START" forState:UIControlStateNormal];
        [_instanceRebootButton setBackgroundColor:[UIColor colorWithHexString:@"c9ced1"]];
        [_instanceTerminateButton setBackgroundColor:[UIColor colorWithHexString:@"e65d65"]];
        _instanceRebootButton.enabled = NO;
        _instanceTerminateButton.enabled = YES;
        if (_instance.state.name == AWSEC2InstanceStateNameStopped || _instance.state.name == AWSEC2InstanceStateNameStopping)
        {
            _instanceStateName.textColor = [UIColor colorWithHexString:@"fe93bf"];
        }
        else if (_instance.state.name == AWSEC2InstanceStateNameTerminated)
        {
            _instanceRebootButton.enabled = NO;
            _instanceStopButton.enabled = NO;
            _instanceTerminateButton.enabled = NO;
            [_instanceStopButton setBackgroundColor:[UIColor colorWithHexString:@"c9ced1"]];
            [_instanceRebootButton setBackgroundColor:[UIColor colorWithHexString:@"c9ced1"]];
            [_instanceTerminateButton setBackgroundColor:[UIColor colorWithHexString:@"c9ced1"]];
        }
        else
        {
            _instanceStateName.textColor = [UIColor colorWithHexString:@"656565"];
//            [_instanceStopButton setTitle:@"STOP" forState:UIControlStateNormal];
        }
    }
    
}

- (void)networkStarted
{
    UIActivityIndicatorView *iView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:iView];
    [iView startAnimating];
    self.navigationItem.rightBarButtonItem = item;
}
- (void)networkStopped
{
    self.navigationItem.rightBarButtonItem = _refreshButton;
    [self loadInstanceDetails];
}

- (void)reboot:(UIButton *)sender
{
    [self networkStarted];
    if (!_rebootRequest)
    {
        _rebootRequest = [[AWSEC2RebootInstancesRequest alloc] init];
        _rebootRequest.instanceIds = @[_instance.instanceId];
    }
    __block typeof(self) weakSelf = self;
    [[[AWSEC2 defaultEC2] rebootInstances:_rebootRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
        [weakSelf networkStopped];
        if (!task.error)
        {
            
        }
        return nil;
    }];
}
- (void)stopOrStart:(UIButton *)sender
{
    [self networkStarted];
    __block typeof(self) weakSelf = self;
    if (_instance.state.name != AWSEC2InstanceStateNameRunning)
    {
        if (!_startRequest)
        {
            _startRequest = [[AWSEC2StartInstancesRequest alloc] init];
            _startRequest.instanceIds = @[_instance.instanceId];
        }
        [[[AWSEC2 defaultEC2] startInstances:_startRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
            [weakSelf networkStopped];
            if (!task.error)
            {
                
            }
            return nil;
        }];
    }
    else
    {
        if (!_stopRequest)
        {
            _stopRequest = [[AWSEC2StopInstancesRequest alloc] init];
            _stopRequest.instanceIds = @[_instance.instanceId];
        }
        [[[AWSEC2 defaultEC2] stopInstances:_stopRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
            [weakSelf networkStopped];
            if (!task.error)
            {
                _instance.state = [[[(AWSEC2StopInstancesResult *)task.result stoppingInstances] firstObject] currentState];
                [weakSelf loadInstanceDetails];
            }
            return nil;
        }];
    }
    
}

- (void)terminate:(UIButton *)sender
{
    [self networkStarted];
    __block typeof(self) weakSelf = self;
    if (!_terminateRequest)
    {
        _terminateRequest = [[AWSEC2TerminateInstancesRequest alloc] init];
        _terminateRequest.instanceIds = @[_instance.instanceId];
    }
    [[[AWSEC2 defaultEC2] terminateInstances:_terminateRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
        [weakSelf networkStopped];
        if (!task.error)
        {
            
        }
        return nil;
    }];
}

- (IBAction)refreshInstanceDetails:(UIBarButtonItem *)sender
{
    [self networkStarted];
    if (!_describeRequest)
    {
        _describeRequest = [[AWSEC2DescribeInstancesRequest alloc] init];
        _describeRequest.instanceIds = @[_instance.instanceId];
    }
    __block typeof(self) weakSelf = self;
    [[[AWSEC2 defaultEC2] describeInstances:_describeRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
        [weakSelf networkStopped];
        if (!task.error)
        {
            _instance = [[[[(AWSEC2DescribeInstancesResult *)task.result reservations] firstObject] instances] firstObject];
            [weakSelf loadInstanceDetails];
        }
        return nil;
    }];
}
@end
